//
//  UITableView+Extension.swift
//  TodayNews
//
//  Created by monkey on 2020/2/4.
//  Copyright © 2020 itcast. All rights reserved.
//

import UIKit

protocol XGRegisterReusableViewProtocol
{
    static var reuseIdentifier: String {get}
    static var nib: UINib? {get}
}

extension XGRegisterReusableViewProtocol
{
    static var reuseIdentifier: String {
        return "\(self)"
    }
    
    static var nib: UINib? {
        if Bundle.main.path(forResource: "\(self)", ofType: "nib") != nil {
            return UINib(nibName: "\(self)", bundle: nil)
        } else {
            return nil
        }
    }
}

extension UITableView
{
    func xg_registerCell<T: UITableViewCell>(cellType: T.Type) -> Void where T: XGRegisterReusableViewProtocol
    {
        if let nib = T.nib {
            register(nib, forCellReuseIdentifier: T.reuseIdentifier)
        } else {
            register(cellType, forCellReuseIdentifier: T.reuseIdentifier)
        }
    }
    
    func xg_dequeueReusableCell<T: UITableViewCell>(indexPath: IndexPath) -> T where T: XGRegisterReusableViewProtocol
    {
        return dequeueReusableCell(withIdentifier: T.reuseIdentifier, for: indexPath) as! T
    }
    
    func xg_registerHeaderFooterView<T: UITableViewHeaderFooterView>(viewType: T.Type) -> Void where T: XGRegisterReusableViewProtocol
    {
        if let nib = T.nib {
            register(nib, forHeaderFooterViewReuseIdentifier: T.reuseIdentifier)
        } else {
            register(viewType, forHeaderFooterViewReuseIdentifier: T.reuseIdentifier)
        }
    }
    
    func xg_dequeueReusableHeaderFooterView<T: UITableViewHeaderFooterView>() -> T where T: XGRegisterReusableViewProtocol
    {
        return dequeueReusableHeaderFooterView(withIdentifier: T.reuseIdentifier) as! T
    }
}

extension UICollectionView
{
    func xg_registerCell<T: UICollectionViewCell>(cellType: T.Type) -> Void where T: XGRegisterReusableViewProtocol
    {
        if let nib = T.nib {
            register(nib, forCellWithReuseIdentifier: T.reuseIdentifier)
        } else {
            register(cellType, forCellWithReuseIdentifier: T.reuseIdentifier)
        }
    }

    func xg_dequeueReusableCell<T: UICollectionViewCell>(indexPath: IndexPath) -> T where T: XGRegisterReusableViewProtocol
    {
        return dequeueReusableCell(withReuseIdentifier: T.reuseIdentifier, for: indexPath) as! T
    }
}
